const App = {
    mixins: [Save],//配置文件，路径/utils/mixins.js
    data() {
        return {
            loading2: false,
            loading: false,
            category: [],
            village: [],
            member: [],
            person: [],
            city: [],
            city1: [],
            qwer: [],
            childDataForm1: [{}],
            is: true,
            cityValue: ["230000", "232700", "232723"],
            cityValue1: [],
            is: true,
            // nextUserShow: false,
            Userid: "",
            Action_type: [
                // 处理结果
                // { value: "分配", label: "分配" },
                // { value: "处理中", label: "处理中" },
                { value: "已处理", label: "已处理" },
                { value: "拒绝", label: "拒绝" },
            ],

            ruleSets: {
                '分配': [{ required: true, message: '下一处理人必填', trigger: 'change' }],
                '处理中': [{ required: true, message: '处理用时(天数)', trigger: 'blur' }],
            },
            showDialog: false,
            organization: [],
        };
    },
    mounted() {

        // console.log('用户名为：'+getCookie('user'));
        this.Userid = getCookie('user');
        this.getCity();
        this.getCategory();
        if (this.action == "Add") {
            this.changeCity(this.cityValue);
        }
        this.getmember();
        this.Getorganization();
        // let str=this.dataForm.status;
        // this.dataForm.status = "处理";
    },
    computed: {
        filteredChildData() {
            return this.childDataForm.filter(item =>
                item.Row_Status != '1' //&& item.processor_id==='230106200105091715'
                // 其他条件...
            );
        }
    },
    watch: {


        //     selectedOption(newVal) {
        //   // 根据 newVal 设置 showControl 的值，例如：
        //   this.showControl = newVal === 'option2'; // 仅当选择 'Option 2' 时显示控件
        // },
        //     "dataForm.status"(val) {
        //         let _this = this;
        //         let str = val;
        //         _this.dataForm.status = "处理";
        //     },
        "dataForm.Village_SerialNumber"(val) {
            if (this.action == "Modify" && this.is) {
                this.is = false;
                let str = this.dataForm.Village_SerialNumber;
                console.log(this.dataForm);
                if (str.substring(0, 6)) {
                    $.ajax({
                        headers: requestHeaders(),
                        url: `${mh}/clientOperation/getDistrictTree`,
                        type: "GET",
                        data: {
                            DistrictCode: str.substring(0, 6),
                        },
                        success: (data) => {
                            this.city1 = data[0].children;
                            if (str.length != 9) {
                                this.cityValue1 = [str.substring(0, 9), str];
                            } else {
                                this.cityValue1 = [str];
                            }
                            this.cityValue = [
                                str.substring(0, 2) + "0000",
                                str.substring(0, 4) + "00",
                                str.substring(0, 6),
                            ];
                        },
                        complete: (XMLHttpRequest) => {
                            requestPretreatment(XMLHttpRequest);
                        },
                        dataType: "json",
                    });
                }
            }
        },
        "dataForm.Address": {
            handler(newVal, oldVal) {
                console.log("地址值变化了:", newVal);

                // 这里可以添加地址变化时的处理逻辑
                // 例如：自动更新坐标
                // map.clearOverlays();

                // 重置全局坐标点（解决多次搜索时的坐标残留问题）
                bd09Point = null;
            },
            deep: false, // 不需要深度监听，因为Address是基本类型
            immediate: false, // 是否在初始化时立即执行一次
        },
        // 新增：监听 dataForm.Coord 的变化
        "dataForm.Coord": {
            handler(newVal, oldVal) {
                console.log("坐标值变化了:", newVal);

                // 防止空值或无效值导致错误
                if (!newVal || newVal === "[]") return;

                try {
                    // 解析坐标值
                    const values = JSON.parse(newVal);
                    const lng = values[0];
                    const lat = values[1];

                    // 检查地图对象是否存在
                    if (window.map) {
                        // 更新地图中心点
                        window.map.centerAndZoom(new window.TLngLat(lng, lat), window.zoom || 12);

                        // 更新或创建标注
                        if (window.marker) {
                            window.map.removeOverLay(window.marker);
                        }
                        window.marker = new window.TMarker(new window.TLngLat(lng, lat));
                        window.map.addOverLay(window.marker);

                        console.log("地图已更新到坐标:", lng, lat);
                    } else {
                        console.warn("地图对象未初始化，请确保 onLoad 函数已执行");
                    }
                } catch (error) {
                    console.error("坐标解析失败:", error);
                }
            },
            deep: false,
            immediate: true // 初始化时立即执行一次，确保页面加载时地图显示正确
        },
    },
    methods: {
        Getorganization() {
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryForObtainingTrees`,
                type: "GET",
                data: {
                    TableName: 'government_agencies',
                    NodeCode: "",
                },
                success: (data) => {
                    this.organization = data; // 直接使用 this
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json",
            });
        },
        preview(row) {
            this.fileUrl = photo + row.file_name;
            this.showDialog = true;
        },
        async download(row) {
            // if (row.file_name) {
            //     window.location.href = photo + row.file_name;
            // }
            let apiUrl = photo + row.file_name;
            let fileName = apiUrl.split('/').pop();
            
            try {
                const response = await fetch(apiUrl);
                const blob = await response.blob();
                const url = window.URL.createObjectURL(blob);
                
                const a = document.createElement('a');
                a.href = url;
                a.download = fileName || 'download';
                document.body.appendChild(a);
                a.click();
                
                // 清理
                setTimeout(() => {
                    document.body.removeChild(a);
                    window.URL.revokeObjectURL(url);
                }, 100);
            } catch (error) {
                console.error('下载失败:', error);
            }
        },
        Rules_next_processor_id(action_type, value, callback) {
            // console.log(action_type);

            if (action_type === '分配' || action_type === '处理中') {
                if (value === '' || value === undefined) {
                    callback(new Error('下一处理人必填'));
                }
                else {
                    callback();
                }
            } else {
                callback();
            }
        },

        Rules_execdays(action_type, value, callback) {
            // console.log(action_type);

            if (action_type == '处理中' && (value === '' || value === undefined)) {
                callback(new Error('处理用时(天数)必填'));
            } else {
                callback();
            }
        },

        getFieldRulesprocessor(type) {

            if (type === '分配') {
                return this.ruleSets[type] || []
            } else {
                return [];
            }
        },

        getFieldRulesexecdays(type) {

            if (type === '处理中') {
                return this.ruleSets[type] || []
            }
            else {
                return [];
            }
        },

        changeAction_type(val, item) {
            // console.log(val);
            // console.log(item);
            // console.log(item.next_processor_id);
            // item.next_processor_id = '';
            // item.execdays = '';
            // this.$nextTick(()=>{
            //     this.$forceUpdate()
            // })

            // 
            // if (val == '处理中') {
            //     item.next_processor_id = item.processor_id;
            // }
            // else {
            //     item.next_processor_id = '';
            // }
            // if (val.length > 0) {
            //     if (val == "分配") {
            //         this.nextUserShow = true;
            //     } else {
            //         this.nextUserShow = false;
            //     }
            // }else{
            //     this.nextUserShow = false;
            // }
            this.dataForm.status = val;
        },
        changeCity(val) {
            if (val.length > 0) {
                $.ajax({
                    headers: requestHeaders(),
                    url: `${mh}/clientOperation/getDistrictTree`,
                    type: "GET",
                    data: {
                        DistrictCode: val[2],
                    },
                    success: (data) => {
                        this.city1 = data[0].children;
                    },
                    complete: (XMLHttpRequest) => {
                        requestPretreatment(XMLHttpRequest);
                    },
                    dataType: "json",
                });
            }
        },
        getmember() {
            let str = '';
            str = " where government_member_information.Row_Status='0'";
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryBySQLSerialNumber`,
                method: "post",
                data: {
                    SQLSerialNumber: "SQL_GOVMember_Query",
                    Condition: '',
                    ExtensionCondition: window.btoa(unescape(encodeURIComponent(str)))
                },
                success: (res) => {
                    this.member = res;
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                },
            });
        },

        getCity() {
            $.ajax({
                url: `${absolutepath()}api/Districtjl.json`,
                method: "get",
                success: (data) => {
                    data.forEach((item) => {
                        item.children.forEach((ite) => {
                            ite.children.forEach((it) => {
                                it.children = undefined;
                            });
                        });
                    });
                    this.city = data;
                },
            });
        },

        getCategory() {
            //类别 SQL_complaint_categoriesMoji
            let str = '';
            str = " where  Row_Status='0' and category_id not in ( select distinct Parent_SerialNumber from complaints_categories) order by Parent_SerialNumber";
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryBySQLSerialNumber`,
                method: "post",
                data: {
                    SQLSerialNumber: "SQL_complaint_categoriesMoji",
                    Condition: '',
                    ExtensionCondition: window.btoa(unescape(encodeURIComponent(str)))
                },
                success: (res) => {
                    this.category = res;
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                },
            });

        },
        changeCity1(val) {
            //console.log(val);
            if (val.length > 0) {
                this.dataForm.Village_SerialNumber = val[val.length - 1];
                if (this.dataForm.Address) {
                    this.changeAddress(this.dataForm.Address);
                }

            } else {
                this.dataForm.Village_SerialNumber = "";
            }
        },
        async handleSubmit() {
            const allValid = await this.validateAllForms();
            if (allValid) {
                this.loading = true;

                let ls_URL = window.location.href;
                const action = getQueryObject(ls_URL, "action");   // 获取 action 参数
                let lJSONObject_Data_Options = new Object();
                lJSONObject_Data_Options = JSON.parse(document.getElementById("MainTable").getAttribute("data-options"));

                let ls_MainTableName = lJSONObject_Data_Options.TableName;
                let ls_DataForm = lJSONObject_Data_Options.form;
                let ls_primary_key = lJSONObject_Data_Options.primary_key;

                let Co_trackid = '';
                let Execlog = [];
                //给childDataForm最后一条赋值trackid
                Co_trackid = getCookie("user") + Date.now().toString();
                this.childDataForm[this.childDataForm.length - 1].complaints_processing_records_trackid = Co_trackid;

                //没有子表下面内容就会报错，try/catch抛出异常
                try {
                    //可能涉及多个子表
                    document.getElementById("ChildTable").querySelectorAll(".el-descriptions").forEach(item => {
                        if (item.hasAttribute('data-options')) {
                            let lJSONObject_ChildData_Options = new Object();
                            lJSONObject_ChildData_Options = JSON.parse(item.getAttribute("data-options"));

                            let ls_ChildTableName = lJSONObject_ChildData_Options.TableName;
                            let ls_ChildDataForm = lJSONObject_ChildData_Options.form;
                            // let ls_ParentTableName = lJSONObject_ChildData_Options.ParentTableName;
                            if (this[ls_DataForm][ls_primary_key]) {
                                this[ls_ChildDataForm].forEach(item => {
                                    item[ls_primary_key] = this[ls_DataForm][ls_primary_key];
                                })
                            }
                            //建立子表结构体
                            let JSONArray_ChildRecord = new Array();
                            JSONArray_ChildRecord = this[ls_ChildDataForm];
                            if (!this[ls_DataForm].Children) {
                                this[ls_DataForm].Children = new Object();
                            }
                            this[ls_DataForm].Children[ls_ChildTableName] = JSONArray_ChildRecord;
                        }
                    })
                } catch (error) {

                }
                //建立新增提交结构
                let lJSONObject_DataSet = new Object();
                if (action == 'Add') {
                    if (this.nodeKey) {
                        this[ls_DataForm].Parent_SerialNumber = this.nodeKey;
                    }
                    let lJSONArray_Record = new Array();
                    lJSONArray_Record.push(this[ls_DataForm]);
                    let lJSONObject_Table = new Object();
                    lJSONObject_Table[ls_MainTableName] = lJSONArray_Record;
                    lJSONObject_DataSet[action] = lJSONObject_Table;
                } else if (action == 'Modify') {
                    const { add, modify } = this.deal(this[ls_DataForm]);
                    let lJSONArray_Record = new Array();
                    lJSONArray_Record.push(modify);

                    let lJSONObject_Table = new Object();
                    lJSONObject_Table[ls_MainTableName] = lJSONArray_Record;

                    lJSONObject_DataSet[action] = lJSONObject_Table;
                    lJSONObject_DataSet['Add'] = new Object();
                    if (add != null) {
                        let lJSONArray_Record_Add = new Array();
                        lJSONArray_Record_Add.push(add);

                        let lJSONObject_Table_Add = new Object();
                        lJSONObject_Table_Add[ls_MainTableName] = lJSONArray_Record_Add;

                        lJSONObject_DataSet['Add'] = lJSONObject_Table_Add;
                    }

                    //增加日志
                    Execlog = [{
                        BusinessName: '事件处理',
                        complaints_trackid: this[ls_DataForm].complaints_trackid,
                        Co_trackid: Co_trackid,
                        ActionName: "事件处理",
                        Memo: "事件处理",
                    }]

                    //插入流水表
                    lJSONObject_DataSet['Add']["complaints_Execlog"] = Execlog;
                }
                console.log(lJSONObject_DataSet);
                let Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
                if (!lJSONObject_DataSet['Add']) {
                    lJSONObject_DataSet['Add'] = new Object();
                }
                lJSONObject_DataSet['Add']['base_operation_log'] = [{
                    Operation_Type: '0',
                    Operation_Path: this.relativePath,
                    Operation_Main,
                    Operation_Interface: "generalSaveByRequestBody",
                    Operation_IP: getIpAddress()
                }]
                submitSave(lJSONObject_DataSet, (res) => {
                    if (res.Status == 'success') {
                        this.seedMessage();
                        // window.location.href = './index.html'
                        // window.history.go(-1);
                    }
                    this.loading = false;
                })
                // $.ajax({
                //     headers: requestHeaders("JSON"),
                //     url: `${mh}/generalBusiness/generalSaveByRequestBody`,
                //     method: "post",
                //     data: JSON.stringify({
                //         Data: lJSONObject_DataSet,
                //     }),
                //     success: (res) => {
                //         if (res.Status == 'success') {
                //             window.location.href = './index.html'
                //             // window.history.go(-1);
                //         }
                //     },
                //     complete: (XMLHttpRequest) => {
                //         requestPretreatment(XMLHttpRequest);
                //         this.loading = false;
                //     },
                // });
            }
        },

        //详细内容业务种类{{thing1.DATA}}
        // 申请日期{{date3.DATA}}
        // 业务状态{{phrase4.DATA}}
        // 提示说明{{thing5.DATA}}
        seedMessage() {
            //获取人员名称以及OPENID
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryBySQLSerialNumber`,
                method: "post",
                data: {
                    SQLSerialNumber: "SQL_GetUserNameAndOpenID",
                    Condition: '',
                    ExtensionCondition: window.btoa(unescape(encodeURIComponent(" where personal_information.Contact_Phone='" + this.dataForm.Creater_SerialNumber + "'")))
                },
                success: (res1) => {
                    if (res1.length > 0) {
                        const lopenid = res1[0].OpenID;
                        const lname = "事件处理已完成";
                        const lServerdatetime = res1[0].Serverdatetime;
                        //调用消息发送接口
                        $.ajax({
                            headers: requestHeaders('JSON'),
                            url: `${mh}/requestForward/requestForwardForPost?RequestURL=${encodeURIComponent(`/wx/mp/sendMicroProgramTemplateMessage`)}`,
                            method: "POST",
                            data: JSON.stringify({
                                openId: lopenid,
                                templateId: "5BKgBNYKh7th5Ld-kaD91Z1pU2D9u2kHl5I-hxgbtV8",
                                content: {
                                    thing1: { value: lname },
                                    date3: { value: lServerdatetime },
                                    phrase4: { value: '事件处理结果：' + this.dataForm.status },
                                    thing5: { value: this.dataForm.title }
                                }
                            }),
                            success: (res) => {

                            },
                            complete: (XMLHttpRequest) => {
                                requestPretreatment(XMLHttpRequest)
                                window.location.href = './index.html'
                            },

                        });
                    } else {
                        window.location.href = './index.html'
                    }
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                },
            });



        },
        changeAddress(val) {
            console.log("地址值变化了:", val);
            if (!val || this.cityValue1.length === 0) {
                this.dataForm.Coord = "";
                return;
            }
            // 开始加载状态
            this.loading = true;
            console.log("地址值变化，开始解析坐标...");

            let Province = this.city.filter((i) => i.value == this.cityValue[0])[0];
            let City = Province.children.filter(
                (i) => i.value == this.cityValue[1]
            )[0];
            let County = City.children.filter((i) => i.value == this.cityValue[2])[0];
            let Town = this.city1.filter(
                (i) => i.ProvinceNumber == this.cityValue1[0]
            )[0];
            let village = Town.children.filter(
                (i) => i.ProvinceNumber == this.cityValue1[1]
            )[0];
            let Address =
                Province.label +
                City.label +
                County.label +
                Town.Province +
                // village.Province +
                val;
            if (Address) {
                $.ajax({
                    url: `${y}/getAddressResolutionAction`,
                    type: "get",
                    data: {
                        Address: Address,
                    },
                    success: (data) => {
                        console.log(data);
                        console.log(data.Data);
                        console.log(Address);
                        // return;
                        // localSearch.setSearchCompleteCallback((searchResult) => {
                        var poi = data.Data;
                        console.log(poi);

                        let a = poi.lng + "," + poi.lat;
                        console.log(a);

                        if (a) {
                            console.log(a);

                            // 获取BD-09坐标
                            const bd09Lng = poi.lng;
                            const bd09Lat = poi.lat;

                            // 转换为WGS-84坐标
                            const wgs84 = bd09ToWGS84(bd09Lng, bd09Lat);
                            console.log(wgs84);

                            this.dataForm.Coord = "[" + wgs84.lng + "," + wgs84.lat + "]";
                            console.log(this.dataForm.Coord);
                            this.loading = false;
                        } else {
                            alert("未找到该地址！");
                        }

                    },
                    dataType: "json",
                });
            }
        },
    },
};
const { createApp, ref } = Vue;
const app = createApp(App);
app.use(ElementPlus, { locale: zhCn });
//这种方式是引入全部图标，无需单个引入
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component);
}
app.component('yl-upload', ylUpload);
app.component('yl-select', ylSelect);
app.component('yl-text-editor', ylTextEditor);
app.component('yl-online-preview', ylOnlinePreview);
const ElMessage = ElementPlus.ElMessage;
app.mount("#app");
